package com.yixinsoft.basic.web.controller.manage.system;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.yixinsoft.basic.model.manage.system.Resource;
import com.yixinsoft.basic.model.manage.system.ResourceType;
import com.yixinsoft.basic.service.manage.system.ResourceService;

/**
 * Created by hqy on 2016/06/05
 */
@Controller
@RequestMapping("/manage/system/resource")
public class ResourceController {

	@Autowired
	private ResourceService resourceService;
	
	@ModelAttribute("types")
	public ResourceType[] resourceTypes() {
		return ResourceType.values();
	}
	
	@RequiresPermissions("resource:view")
	@RequestMapping(method = RequestMethod.GET)
	public String list(Model model) {
		model.addAttribute("resourceList", resourceService.queryListOrderById());
		return "manage/system/resource/list";
	}
	
	@RequiresPermissions("resource:create")
	@RequestMapping(value = "/appendChild/{parentId}", method = RequestMethod.GET)
	public String appendChild(Model model, @PathVariable Long parentId) {
		Resource parent = resourceService.queryById(parentId);
		Resource child = new Resource();
		child.setParentId(parentId);
		child.setParentIds(parent.makeSelfAsParentIds());
		
		model.addAttribute("parent", parent);
		model.addAttribute("resource", child);
		model.addAttribute("op", "新增子节点");
		return "manage/system/resource/edit";
	}
	
	@RequiresPermissions("resource:create")
	@RequestMapping(value = "/appendChild/{parentId}", method = RequestMethod.POST)
	public String appendChild(Resource resource) {
		resourceService.save(resource);
		return "redirect:/manage/system/resource";
	}
	
	@RequiresPermissions("resource:update")
	@RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
	public String update(Model model, @PathVariable Long id) {
		Resource resource = resourceService.queryById(id);
		model.addAttribute("parent", resourceService.queryById(resource.getParentId()));
		model.addAttribute("resource", resource);
		model.addAttribute("op", "修改");
		return "manage/system/resource/edit";
	}
	
	@RequiresPermissions("resource:update")
	@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
	public String update(Resource resource) {
		resourceService.update(resource);
		return "redirect:/manage/system/resource";
	}
	
	@RequiresPermissions("resource:delete")
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public String delete(Long[] ids) {
		resourceService.deleteByIds(ids);
		return "redirect:/manage/system/resource";
	}
}
